package com.lunevich.json.helpers;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.lunevich.json.common.GetSystemService;

public class HttpManager {
	
	public static final String HTTP_MANAGER = "=HTTP_MANAGER=";
	private DefaultHttpClient defaultHttpClient;
	
	public HttpManager() {
		super();
		defaultHttpClient = new DefaultHttpClient();
	}
	
	public static HttpManager getHttpManager(Context context) {
		return (HttpManager) GetSystemService.get(context, HTTP_MANAGER);
	}

	private String getJSONStringFromUrl(String url, Context context) throws Exception {
		// Setup the get request
		HttpGet httpGetRequest = new HttpGet(url);

		// Execute the request in the client
		HttpResponse httpResponse = defaultHttpClient.execute(httpGetRequest);
		InputStream is = httpResponse.getEntity().getContent();

		// Grab the response
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
		String json = reader.readLine();
		return json;
	}

	public JSONArray getJSONArrayFromUrl(String url, Context context) throws Exception {
		String json = getJSONStringFromUrl(url, context);
		return new JSONArray(json);
	}

	public JSONObject getJSONObjectFromUrl(String url, Context context) throws Exception {
		String json = getJSONStringFromUrl(url, context);
		return new JSONObject(json);
	}
	
	public String getXMLDataFromUrl(String url, Context context) throws Exception {
		HttpGet getMethod = new HttpGet(url);
		ResponseHandler<String> res = new BasicResponseHandler();
		String response = defaultHttpClient.execute(getMethod, res);
		return response;
	}
}